import React, { useState, useRef, useEffect } from 'react';
import { Card, Button, message, Spin, Empty, Typography, Form, Input, DatePicker, Select, Space } from 'antd';
import { ScanOutlined, SaveOutlined, EditOutlined, EyeOutlined, ReloadOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { updateDevice } from '../redux/features/deviceSlice';
import { formatDate } from '../utils/tools';
import './ScanQRCodePage.css';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Paragraph } = Typography;

const ScanQRCodePage = () => {
  const [scanning, setScanning] = useState(false);
  const [deviceData, setDeviceData] = useState(null);
  const [editing, setEditing] = useState(false);
  const [form] = Form.useForm();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const streamRef = useRef(null);
  const dispatch = useDispatch();

  // 设备类型选项
  const deviceTypes = [
    '服务器', '网络设备', '存储设备', '安全设备',
    '终端设备', '办公设备', '生产设备', '其他设备'
  ];

  // 检查浏览器是否支持媒体设备
  useEffect(() => {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      setError('您的浏览器不支持摄像头功能，请使用现代浏览器');
    }

    // 清理函数
    return () => {
      if (streamRef.current) {
        streamRef.current.getTracks().forEach(track => track.stop());
      }
    };
  }, []);

  // 启动摄像头并开始扫描
  const startScanning = async () => {
    try {
      setIsLoading(true);
      setError(null);
      setDeviceData(null);
      setEditing(false);

      // 获取媒体设备流
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: 'environment' }
      });
      
      streamRef.current = stream;
      videoRef.current.srcObject = stream;
      
      // 当视频准备好后开始扫描
      videoRef.current.onloadedmetadata = () => {
        videoRef.current.play();
        setScanning(true);
        setIsLoading(false);
        startScanLoop();
      };
    } catch (err) {
      console.error('启动摄像头失败:', err);
      setError('无法访问摄像头，请确保您已授权摄像头访问权限');
      setIsLoading(false);
      message.error('启动摄像头失败');
    }
  };

  // 停止扫描
  const stopScanning = () => {
    setScanning(false);
    if (streamRef.current) {
      streamRef.current.getTracks().forEach(track => track.stop());
    }
  };

  // 开始扫描循环
  const startScanLoop = () => {
    if (!scanning || !videoRef.current || !canvasRef.current) return;

    const video = videoRef.current;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');

    // 设置canvas尺寸与视频尺寸一致
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    // 绘制当前视频帧到canvas
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

    // 获取图像数据（模拟二维码扫描）
    // 实际项目中应该使用jsQR等库进行真正的二维码解析
    setTimeout(() => {
      // 模拟成功扫描到二维码数据
      // 实际项目中应该使用QR码扫描库替换这段代码
      simulateQRScan();
      
      // 继续扫描下一帧
      if (scanning) {
        requestAnimationFrame(startScanLoop);
      }
    }, 1000); // 每1000ms扫描一次
  };

  // 模拟二维码扫描（实际项目中应替换为真实的二维码扫描逻辑）
  const simulateQRScan = () => {
    // 随机决定是否模拟成功扫描
    // 实际项目中应替换为真实的二维码解析逻辑
    if (Math.random() < 0.1) { // 10%的概率模拟扫描成功
      // 模拟的设备数据
      const mockDeviceData = {
        device_name: '测试设备 ' + Math.floor(Math.random() * 1000),
        production_date: formatDate(new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000)),
        device_type: deviceTypes[Math.floor(Math.random() * deviceTypes.length)],
        device_code: 'DEV-' + Math.floor(Math.random() * 10000),
        description: '这是一个测试设备，通过模拟扫描二维码获得'
      };

      handleScanResult(mockDeviceData);
    }
  };

  // 处理扫描结果
  const handleScanResult = (data) => {
    try {
      // 如果data是字符串，则尝试解析为JSON对象
      const deviceInfo = typeof data === 'string' ? JSON.parse(data) : data;
      
      // 验证设备数据
      if (deviceInfo && deviceInfo.device_code) {
        setDeviceData(deviceInfo);
        form.setFieldsValue({
          ...deviceInfo,
          production_date: deviceInfo.production_date ? new Date(deviceInfo.production_date) : null
        });
        stopScanning();
        message.success('扫描成功');
      } else {
        throw new Error('无效的设备数据');
      }
    } catch (err) {
      console.error('解析二维码数据失败:', err);
      message.error('解析二维码数据失败');
    }
  };

  // 编辑设备信息
  const handleEdit = () => {
    setEditing(true);
  };

  // 保存设备信息
  const handleSave = async (values) => {
    try {
      setIsLoading(true);
      
      // 格式化保存数据
      const updatedData = {
        ...values,
        production_date: values.production_date ? formatDate(values.production_date) : null,
        updated_at: formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
      };

      // 调用Redux action更新设备
      await dispatch(updateDevice(updatedData)).unwrap();
      
      setDeviceData(updatedData);
      setEditing(false);
      message.success('设备信息更新成功');
    } catch (error) {
      console.error('更新设备信息失败:', error);
      message.error('更新设备信息失败，请稍后再试');
    } finally {
      setIsLoading(false);
    }
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setEditing(false);
    if (deviceData) {
      form.setFieldsValue({
        ...deviceData,
        production_date: deviceData.production_date ? new Date(deviceData.production_date) : null
      });
    }
  };

  // 重新扫描
  const handleRescan = () => {
    setDeviceData(null);
    setEditing(false);
    startScanning();
  };

  return (
    <div className="scan-qrcode-container">
      <div className="page-header">
        <Title level={3} className="page-title">
          扫描设备二维码
        </Title>
        <Paragraph className="page-description">
          通过摄像头扫描设备上的二维码，快速查看和管理设备信息。
        </Paragraph>
      </div>

      {error && (
        <div className="error-message">
          {typeof error === 'string' ? error : error.message || '发生错误，请稍后再试'}
        </div>
      )}

      <Card className="scan-container">
        {!deviceData ? (
          <div className="scanner-view">
            {isLoading ? (
              <div className="loading-state">
                <Spin size="large" tip="正在启动摄像头..." />
              </div>
            ) : (
              <>:
                <div className="video-container">
                  {scanning ? (
                    <>
                      <video 
                        ref={videoRef} 
                        autoPlay 
                        playsInline 
                        muted 
                        className="scan-video"
                      />
                      <canvas ref={canvasRef} className="scan-canvas" style={{ display: 'none' }} />
                      <div className="scan-frame" />
                      <div className="scan-line" />
                    </>
                  ) : (
                    <div className="no-scan-state">
                      <Empty 
                        image={Empty.PRESENTED_IMAGE_SIMPLE} 
                        description="点击下方按钮开始扫描"
                      />
                    </div>
                  )}
                </div>
                
                <div className="scan-actions">
                  {scanning ? (
                    <Button 
                      danger 
                      icon={<EyeOutlined />} 
                      onClick={stopScanning}
                    >
                      停止扫描
                    </Button>
                  ) : (
                    <Button 
                      type="primary" 
                      icon={<ScanOutlined />} 
                      onClick={startScanning}
                      disabled={!!error}
                    >
                      开始扫描
                    </Button>
                  )}
                </div>
              </>
            )}
          </div>
        ) : (
          <div className="device-info-view">
            <div className="info-header">
              <Title level={4} className="device-name">
                {deviceData.device_name}
              </Title>
              <div className="info-actions">
                <Space size="middle">
                  <Button 
                    icon={<ReloadOutlined />} 
                    onClick={handleRescan}
                  >
                    重新扫描
                  </Button>
                  {!editing ? (
                    <Button 
                      type="primary" 
                      icon={<EditOutlined />} 
                      onClick={handleEdit}
                    >
                      编辑信息
                    </Button>
                  ) : (
                    <Space size="middle">
                      <Button 
                        onClick={handleCancelEdit}
                      >
                        取消
                      </Button>
                      <Button 
                        type="primary" 
                        icon={<SaveOutlined />} 
                        loading={isLoading}
                        onClick={() => form.submit()}
                      >
                        保存
                      </Button>
                    </Space>
                  )}
                </Space>
              </div>
            </div>

            <Form
              form={form}
              layout="vertical"
              onFinish={handleSave}
              className="device-form"
              initialValues={deviceData}
            >
              <div className="form-grid">
                <Form.Item
                  label="设备名称"
                  name="device_name"
                  rules={[
                    { required: true, message: '请输入设备名称' },
                    { max: 100, message: '设备名称不能超过100个字符' }
                  ]}
                >
                  <Input disabled={!editing} />
                </Form.Item>

                <Form.Item
                  label="生产日期"
                  name="production_date"
                  rules={[
                    { required: true, message: '请选择生产日期' }
                  ]}
                >
                  <DatePicker
                    style={{ width: '100%' }}
                    disabled={!editing}
                    maxDate={new Date()}
                  />
                </Form.Item>

                <Form.Item
                  label="设备类型"
                  name="device_type"
                  rules={[
                    { required: true, message: '请选择设备类型' }
                  ]}
                >
                  <Select disabled={!editing}>
                    {deviceTypes.map((type) => (
                      <Option key={type} value={type}>{type}</Option>
                    ))}
                  </Select>
                </Form.Item>

                <Form.Item
                  label="设备编号"
                  name="device_code"
                  rules={[
                    { required: true, message: '请输入设备编号' }
                  ]}
                >
                  <Input disabled />
                </Form.Item>

                <Form.Item
                  label="设备描述"
                  name="description"
                  rules={[
                    { max: 500, message: '设备描述不能超过500个字符' }
                  ]}
                >
                  <TextArea rows={4} disabled={!editing} />
                </Form.Item>
              </div>
            </Form>

            {/* 显示二维码扫描时间或生成时间 */}
            {deviceData.generated_at && (
              <div className="scan-time">
                <span>二维码生成时间: {deviceData.generated_at}</span>
              </div>
            )}
          </div>
        )}
      </Card>

      {/* 使用提示 */}
      <div className="usage-tips">
        <div className="tips-title">使用提示</div>
        <ul className="tips-list">
          <li>确保设备二维码清晰可见，没有遮挡或损坏</li>
          <li>扫描时保持适当距离，使二维码位于扫描框内</li>
          <li>在光线充足的环境下扫描效果更佳</li>
          <li>扫描成功后可以查看和编辑设备信息</li>
        </ul>
      </div>
    </div>
  );
};

export default ScanQRCodePage;